<template>
  <div class="monitor-container">
    <!-- 左侧行程列表 -->
    <div class="trip-list">
      <el-card class="trip-list-card">
        <template #header>
          <div class="card-header">
            <span>实时行程列表</span>
            <div class="header-actions">
              <el-input 
                v-model="searchId"
                placeholder="输入行程ID搜索"
                clearable
                style="width: 180px; margin-right: 10px;"
                @input="filterTrips"
              >
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
              <el-button type="primary" size="small" @click="fetchTripData">
                <el-icon><Refresh /></el-icon>
              </el-button>
              <el-switch
                v-model="autoRefresh"
                active-text="自动刷新"
                @change="toggleAutoRefresh"
              />
            </div>
          </div>
        </template>
        
        <el-table :data="tripList" style="width: 100%" height="calc(100vh - 200px)" @row-click="handleTripClick">
          <el-table-column prop="tripId" label="行程ID" width="180" />
          <el-table-column label="最新位置信息" min-width="200">
            <template #default="scope">
              <div v-if="getLatestData(scope.row)">
                <div>更新时间：{{ getLatestData(scope.row).createTime }}</div>
                <div>已行驶：{{ getLatestData(scope.row).currentDistance.toFixed(2) }}km</div>
                <div>距下一点：{{ getLatestData(scope.row).distanceToDestination.toFixed(2) }}km</div>
                <el-button type="primary" size="small" @click.stop="startPlayback(scope.row)">
                  轨迹回放
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
    
    <!-- 右侧地图 -->
    <div class="map-wrapper">
      <tlbs-map
        ref="mapRef"
        :center="center"
        :zoom="zoom"
        :control="control"
        class="map-container"
        @map_inited="onMapInited"
      >
        <tlbs-multi-label
          ref="labelRef"
          :geometries="geometries"
          :styles="labelStyles"
          :options="labelOptions"
          @click="handleLabelClick"
        />
        <!-- 添加轨迹线图层 -->
        <tlbs-polyline
          v-if="isPlaybackMode"
          :paths="playbackPaths"
          :styles="polylineStyles"
        />
      </tlbs-map>

      <!-- 轨迹回放控制面板 -->
      <div v-if="isPlaybackMode" class="playback-panel">
        <div class="playback-info">
          <span>行程 {{ currentPlayback?.tripId }}</span>
          <span>{{ currentPlayback?.currentPoint?.createTime }}</span>
        </div>
        <div class="playback-progress">
          <el-slider
            v-model="playbackProgress"
            :max="playbackTotal"
            :format-tooltip="formatPlaybackProgress"
            @change="handlePlaybackProgressChange"
            :disabled="isPlaying"
          />
        </div>
        <div class="playback-controls">
          <el-button-group>
            <el-button 
              type="primary"
              :icon="isPlaying ? VideoPause : VideoPlay"
              @click="isPlaying ? playbackPause() : playbackPlay()"
            >
              {{ isPlaying ? '暂停' : '播放' }}
            </el-button>
            <el-button 
              type="info"
              :icon="RefreshLeft"
              @click="playbackReset"
              :disabled="isPlaying"
            >
              重置
            </el-button>
          </el-button-group>
          <el-select 
            v-model="playbackSpeed" 
            style="width: 100px"
            :disabled="isPlaying"
          >
              <el-option label="0.5x" :value="0.5" />
              <el-option label="1x" :value="1" />
              <el-option label="2x" :value="2" />
              <el-option label="4x" :value="4" />
            </el-select>
          <el-button 
            type="danger" 
            @click="stopPlayback"
            :disabled="isPlaying"
          >
            退出回放
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup>
import { ref, onMounted, onBeforeUnmount, computed, watch } from 'vue'
import { getTripList } from '@/api/tripInfo'
import { ElMessage } from 'element-plus'
import { VideoPlay, VideoPause, RefreshLeft, Search } from '@element-plus/icons-vue'

// 地图容器引用
const mapRef = ref(null)
const labelRef = ref(null)

// 地图控制参数
const center = ref({ lat: 36.5535800, lng: 116.7519900 }) // 根据数据中的坐标设置默认中心
const zoom = ref(13)
const control = ref({
  scale: {},
  zoom: {
    position: 'topRight',
  }
})

// 文字标记样式
const labelStyles = ref({
  'trip': {
    color: '#FFFFFF',
    size: 14,
    fontWeight: 'bold',
    offset: { x: 0, y: 0 },
    angle: 0,
    width: 40,
    height: 40,
    backgroundColor: '#FF4D4F',
    borderWidth: 0,
    borderRadius: 20,
    alignment: 'center',
    verticalAlignment: 'middle',
    boxShadow: '0 2px 6px rgba(0,0,0,0.2)'
  }
})

// 文字标记选项
const labelOptions = ref({
  collisionOptions: {
    sameSource: true
  }
})

// 标记数据
const geometries = ref([])

// 行程数据
const tripList = ref([])
// 原始行程数据，用于过滤
const originalTripList = ref([])
// 行程ID搜索
const searchId = ref('')

// 获取实时行程数据
const fetchTripData = async () => {
  try {
    const res = await getTripList()
    if (res.code === 1) {
      originalTripList.value = res.data
      tripList.value = [...originalTripList.value]
      updateLabels()
      console.log('获取实时行程数据成功：', tripList.value)
    }
  } catch (error) {
    console.error('获取实时行程数据失败：', error)
    ElMessage.error('获取实时行程数据失败')
  }
}

// 过滤行程
const filterTrips = () => {
  if (!searchId.value) {
    // 如果搜索框为空，显示全部行程
    tripList.value = [...originalTripList.value]
  } else {
    // 根据行程ID过滤
    tripList.value = originalTripList.value.filter(trip => 
      trip.tripId && trip.tripId.toString().includes(searchId.value)
    )
  }
  // 更新地图上的标记
  updateLabels()
}

// 获取行程最新位置数据
const getLatestData = (trip) => {
  if (!trip.tripDataList || trip.tripDataList.length === 0) return null
  return trip.tripDataList[trip.tripDataList.length - 1]
}

// 更新标记
const updateLabels = () => {
  geometries.value = tripList.value.map(trip => {
    const latestData = getLatestData(trip)
    if (!latestData) return null

    return {
      id: trip.tripId,
      position: {
        lat: latestData.latitude,
        lng: latestData.longitude
      },
      styleId: 'trip',
      content: '行程',
      properties: {
        createTime: latestData.createTime,
        currentDistance: latestData.currentDistance,
        distanceToDestination: latestData.distanceToDestination
      }
    }
  }).filter(item => item !== null)
}

// 处理行程点击
const handleTripClick = (row) => {
  const latestData = getLatestData(row)
  if (!latestData || !mapRef.value) return

  // 将地图中心移动到选中的行程位置
  mapRef.value.map.setCenter(new TMap.LatLng(latestData.latitude, latestData.longitude))
}

// 处理标记点击
const handleLabelClick = (evt) => {
  const label = evt.geometry
  if (!label || !mapRef.value) return

  // 显示信息窗口
  showTripInfo(label)
}

// 显示行程信息窗口
let infoWindow = null
const showTripInfo = (label) => {
  if (!mapRef.value) return

  if (!infoWindow) {
    infoWindow = new TMap.InfoWindow({
      map: mapRef.value.map,
      position: new TMap.LatLng(label.position.lat, label.position.lng),
      content: '',
      offset: { x: 0, y: -20 }
    })
  }

  const content = `
    <div class="info-window">
      <h3>行程 ${label.id}</h3>
      <p>更新时间：${label.properties.createTime}</p>
      <p>已行驶：${label.properties.currentDistance.toFixed(2)}km</p>
      <p>距下一点：${label.properties.distanceToDestination.toFixed(2)}km</p>
    </div>
  `
  
  infoWindow.setContent(content)
  infoWindow.setPosition(new TMap.LatLng(label.position.lat, label.position.lng))
  infoWindow.open()
}

// 地图初始化完成
const onMapInited = () => {
  console.log('地图加载完成')
  fetchTripData()
}

// 自动刷新相关
const autoRefresh = ref(false)
let refreshTimer = null

// 开启/关闭自动刷新
const toggleAutoRefresh = (val) => {
  if (val) {
    refreshTimer = setInterval(() => {
      fetchTripData()
    }, 30000) // 每30秒刷新一次
    ElMessage.success('已开启自动刷新（30秒）')
  } else {
    if (refreshTimer) {
      clearInterval(refreshTimer)
      refreshTimer = null
    }
    ElMessage.info('已关闭自动刷新')
  }
}

// 轨迹回放相关
const isPlaybackMode = ref(false)
const currentPlayback = ref(null)
const playbackProgress = ref(0)
const playbackTotal = ref(0)
const playbackSpeed = ref(1)
const isPlaying = ref(false)
let playbackTimer = null

// 开始轨迹回放
const startPlayback = (trip) => {
  if (!trip.tripDataList || trip.tripDataList.length === 0) {
    ElMessage.warning('没有轨迹数据可供回放')
    return
  }
  
  // 初始化回放状态
  currentPlayback.value = {
    tripId: trip.tripId,
    points: trip.tripDataList,
    currentPoint: trip.tripDataList[0]
  }
  playbackProgress.value = 0
  playbackTotal.value = trip.tripDataList.length - 1
  isPlaybackMode.value = true
  isPlaying.value = false

  // 更新地图显示
  updatePlaybackMarker()
  
  // 调整地图视野以显示完整轨迹
  if (mapRef.value) {
    const bounds = new TMap.LatLngBounds()
    trip.tripDataList.forEach(point => {
      bounds.extend(new TMap.LatLng(point.latitude, point.longitude))
    })
    mapRef.value.map.fitBounds(bounds, {
      padding: 100
    })
  }

  // 自动开始播放
  playbackPlay()
}

// 轨迹线样式
const polylineStyles = ref({
  'default': {
    color: '#3777FF', // 蓝色轨迹线
    width: 4,
    borderWidth: 2,
    borderColor: '#FFFFFF',
    lineCap: 'round',
    opacity: 0.8
  },
  'passed': {
    color: '#67C23A', // 已经过的轨迹用绿色显示
    width: 4,
    borderWidth: 2,
    borderColor: '#FFFFFF',
    lineCap: 'round',
    opacity: 0.8
  }
})

// 计算轨迹线路径
const playbackPaths = computed(() => {
  if (!currentPlayback.value || !currentPlayback.value.points) return []

  const points = currentPlayback.value.points
  const currentIndex = playbackProgress.value
  
  // 将轨迹分为已经过和未经过两部分
  const passedPath = points.slice(0, currentIndex + 1).map(point => ({
    lat: point.latitude,
    lng: point.longitude
  }))
  
  const remainingPath = points.slice(currentIndex).map(point => ({
    lat: point.latitude,
    lng: point.longitude
  }))

  return [
    {
      styleId: 'passed',
      paths: passedPath
    },
    {
      styleId: 'default',
      paths: remainingPath
    }
  ]
})

// 更新标记位置（添加平滑移动效果）
const updatePlaybackMarker = () => {
  console.log('更新标记位置') // 添加调试日志
  if (!currentPlayback.value?.currentPoint) return

  const currentPoint = currentPlayback.value.currentPoint
  const nextPoint = currentPlayback.value.points[playbackProgress.value + 1]
  
  // 如果有下一个点，计算插值动画
  if (nextPoint && isPlaying.value) {
    const startLat = currentPoint.latitude
    const startLng = currentPoint.longitude
    const endLat = nextPoint.latitude
    const endLng = nextPoint.longitude
    
    // 创建10帧的平滑动画
    const frames = 10
    let currentFrame = 0
    
    const animate = () => {
      if (currentFrame >= frames || !isPlaying.value) {
        return
      }
      
      const progress = currentFrame / frames
      const lat = startLat + (endLat - startLat) * progress
      const lng = startLng + (endLng - startLng) * progress
      
      geometries.value = [{
        id: 'playback',
        position: { lat, lng },
        styleId: 'trip',
        content: '行程',
        properties: currentPoint
      }]
      
      currentFrame++
      requestAnimationFrame(animate)
    }
    
    animate()
  } else {
    // 如果没有下一个点或暂停状态，直接更新位置
    geometries.value = [{
      id: 'playback',
      position: {
        lat: currentPoint.latitude,
        lng: currentPoint.longitude
      },
      styleId: 'trip',
      content: '行程',
      properties: currentPoint
    }]
  }
}

// 播放速度监听
watch(playbackSpeed, (newSpeed) => {
  if (isPlaying.value) {
    // 重新启动播放器以应用新的速度
    playbackPause()
    playbackPlay()
  }
})

// 修改播放控制逻辑
const playbackPlay = () => {
  console.log('开始播放', currentPlayback.value)
  if (!currentPlayback.value) {
    ElMessage.warning('没有可播放的轨迹数据')
    return
  }
  
  if (playbackProgress.value >= playbackTotal.value) {
    playbackProgress.value = 0
  }
  
  isPlaying.value = true
  const baseInterval = 1000 // 基础间隔1秒

  // 清除可能存在的旧定时器
  if (playbackTimer) {
    clearInterval(playbackTimer)
  }
  
  playbackTimer = setInterval(() => {
    console.log('播放进度：', playbackProgress.value, '总进度：', playbackTotal.value)
    if (playbackProgress.value >= playbackTotal.value) {
      playbackPause()
      ElMessage.info('播放完成')
      return
    }
    playbackProgress.value++
    handlePlaybackProgressChange(playbackProgress.value)
  }, baseInterval / playbackSpeed.value)
}

const playbackPause = () => {
  console.log('暂停播放')
  isPlaying.value = false
  if (playbackTimer) {
    clearInterval(playbackTimer)
    playbackTimer = null
  }
}

const playbackReset = () => {
  console.log('重置播放')
  if (isPlaying.value) {
    ElMessage.warning('请先暂停播放')
    return
  }
  playbackPause()
  playbackProgress.value = 0
  handlePlaybackProgressChange(0)
  ElMessage.success('已重置到起点')
}

// 处理进度变化
const handlePlaybackProgressChange = (index) => {
  console.log('进度变化：', index)
  if (!currentPlayback.value || !currentPlayback.value.points[index]) return
  
  currentPlayback.value.currentPoint = currentPlayback.value.points[index]
  updatePlaybackMarker()
}

// 格式化进度提示
const formatPlaybackProgress = (val) => {
  if (!currentPlayback.value?.points[val]) return ''
  return currentPlayback.value.points[val].createTime
}

// 停止回放
const stopPlayback = () => {
  console.log('停止回放')
  if (isPlaying.value) {
    ElMessage.warning('请先暂停播放')
    return
  }
  playbackPause()
  isPlaybackMode.value = false
  currentPlayback.value = null
  // 恢复实时数据显示
  updateLabels()
  ElMessage.success('已退出回放模式')
}

// 组件卸载前清理
onBeforeUnmount(() => {
  if (refreshTimer) {
    clearInterval(refreshTimer)
    refreshTimer = null
  }
  if (playbackTimer) {
    clearInterval(playbackTimer)
    playbackTimer = null
  }
})
</script>
<style scoped>
.monitor-container {
  display: flex;
  padding: 20px;
  gap: 20px;
  height: calc(100vh - 40px);
}

.trip-list {
  width: 500px;
  flex-shrink: 0;
}

.trip-list-card {
  height: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.map-wrapper {
  flex: 1;
  height: 100%;
  position: relative;
}

.map-container {
  width: 100%;
  height: 100%;
}

:deep(.info-window) {
  padding: 10px;
  max-width: 300px;
}

:deep(.info-window h3) {
  margin: 0 0 10px 0;
  color: #303133;
  font-size: 16px;
}

:deep(.info-window p) {
  margin: 5px 0;
  color: #606266;
  font-size: 14px;
}

.playback-panel {
  position: absolute;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  background-color: rgba(255, 255, 255, 0.95);
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  width: 80%;
  max-width: 600px;
  z-index: 1000;
}

.playback-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
  font-size: 14px;
  color: #606266;
  font-weight: bold;
}

.playback-progress {
  margin-bottom: 20px;
}

.playback-controls {
  display: flex;
  justify-content: center;
  gap: 15px;
  align-items: center;
}

:deep(.el-slider) {
  margin-top: 8px;
}

:deep(.el-button-group) {
  margin-right: 10px;
}

:deep(.el-select) {
  margin: 0 10px;
}
</style> 